package com.agree.util.excel.handlers.db;

import com.agree.util.excel.config.Configuration;
import com.agree.util.excel.entity.TableInfo;

import java.sql.*;
import java.util.List;

/**
 * Created by wangmu on 2017/12/1.
 */
public abstract class DBHandler {

    protected String driveClassName;

    protected String url;

    protected String password;

    protected String username;

    protected Connection connection;

    protected Configuration configuration;

    public DBHandler(Configuration configuration) {
        this.configuration = configuration;
        this.driveClassName = configuration.dbConfig().driverClassName();
        this.url = configuration.dbConfig().url();
        this.password = configuration.dbConfig().password();
        this.username = configuration.dbConfig().username();
    }

    public DBHandler(String driveClassName, String url, String username, String password) {
        this.driveClassName = driveClassName;
        this.url = url;
        this.password = password;
        this.username = username;
    }

    protected Connection getConnection(){
        //load driver
        try {
            Class.forName(driveClassName);
        } catch (ClassNotFoundException  e) {
            System.out.println("load driver failed!");
            e.printStackTrace();
        }
        //connect db
        try {
            this.connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            System.out.println("connect failed!");
            e.printStackTrace();
        }
        return this.connection;
    }

    protected abstract ResultSet getTableInfoResult(String tableName) throws SQLException;
    protected abstract ResultSet getTableFieldsResult(String tableName) throws SQLException;

    protected ResultSet commonQuery(String sql,String tableName) throws SQLException {
        //获取连接
        Connection connection = this.getConnection();
        //获取sql语句
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //设置占位符
        preparedStatement.setString(1,tableName);
        //执行获取结果集
        ResultSet resultSet = preparedStatement.executeQuery();
        return resultSet;
    }

    protected void closeConnection(){
        if(connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                connection = null;
            }
        }
    }

    protected abstract TableInfo getTableInfo(String tableName);

    protected abstract List<TableInfo> getAllTableInfo(String[] tableNames);

    public abstract List<TableInfo> getAllTableInfo();
}
